<template>
  <div class="borrow-records-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>借阅记录</span>
          <el-select
            v-model="status"
            placeholder="筛选状态"
            clearable
            style="width: 200px"
            @change="handleSearch"
          >
            <el-option label="已借阅" value="borrowed" />
            <el-option label="待归还" value="pending_return" />
            <el-option label="已归还" value="returned" />
          </el-select>
        </div>
      </template>

      <el-table :data="records" v-loading="loading" stripe>
        <el-table-column prop="title" label="书名" width="180" />
        <el-table-column prop="author" label="作者" width="120" />
        <el-table-column prop="isbn" label="ISBN" width="130" />
        <el-table-column prop="category" label="分类" width="100" />
        <el-table-column 
          v-if="authStore.isAdmin" 
          prop="username" 
          label="借阅人" 
          width="120" 
        />
        <el-table-column prop="borrowDate" label="借阅日期" width="160">
          <template #default="{ row }">
            {{ formatDate(row.borrowDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="returnDate" label="归还日期" width="160">
          <template #default="{ row }">
            {{ formatDate(row.returnDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag v-if="row.status === 'borrowed'" type="success">已借阅</el-tag>
            <el-tag v-else-if="row.status === 'pending_return'" type="warning">待确认归还</el-tag>
            <el-tag v-else type="info">已归还</el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useAuthStore } from '../stores/auth'
import { borrowAPI } from '../services/api'

const authStore = useAuthStore()
const records = ref([])
const loading = ref(false)
const status = ref('')

const fetchRecords = async () => {
  loading.value = true
  try {
    const response = await borrowAPI.getBorrowRecords({
      status: status.value || undefined
    })
    records.value = response.records || []
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '获取借阅记录失败')
  } finally {
    loading.value = false
  }
}

const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleString('zh-CN')
}

const handleSearch = () => {
  fetchRecords()
}

onMounted(() => {
  fetchRecords()
})
</script>

<style scoped>
.borrow-records-container {
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>

